<?php
class Downloader {

    private static $BUFFER_SIZE = 8192;
    private $handle;
    private $totalSize = 0;
    private $active;
    private $destination;
    private $dstHandle;

    public function __construct($url, $dst) {
        $this->handle = fopen($url, 'r');
        $curlHandle = curl_init($url);
        curl_setopt($curlHandle, CURLOPT_NOBODY, true);
        curl_exec($curlHandle);
        $info = curl_getinfo($curlHandle);
        $this->totalSize = $info["download_content_length"];
        $this->destination = $dst;
        $this->dstHandle =  fopen($dst, 'w');
        if (!$this->dstHandle || !$this->handle) {
            $this->active = "error";
        } else {
            $this->active = "init";
        }
        curl_close($curlHandle);
    }

    public function start($jsonFile) {
        $json = json_decode(file_get_contents($jsonFile), true);
        $this->active = 'started';
        $json["state"] = $this->active;
        while ($this->handle && !feof($this->handle)) {
            $read = fread($this->handle, self::$BUFFER_SIZE);
            fwrite($this->dstHandle, $read);
            $json["currentSize"] = ftell($this->dstHandle);
            file_put_contents($jsonFile, json_encode($json));
        }
        fclose($this->handle);
        fclose($this->dstHandle);
        $this->active = 'complete';
        $json["state"] = $this->active;
        file_put_contents($jsonFile, json_encode($json));
    }

    public function getState() {
        return $this->active;
    }

    public function getTotalSize() {
        return $this->totalSize;
    }
}
